package edu.polsl.bio.str.node.logic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * //todo class description
 * <p/>
 * Created on: Jul 19, 2011 5:06:50 PM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class ConnectionLossHandlerImpl implements ConnectionLossHandler, Runnable {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(ConnectionLossHandlerImpl.class.getName());

  private static final int MINUTE_IN_MILLIS = 60000;

  private NodeContext nodeContext;

  private NodeControlBean nodeControlBean;

  private int reconnectIntervalInMin;

  private boolean isScheduled = false;

  @Override
  public synchronized void handleConnectionLoss() {
    log.debug("Handling connection loss");
    if (isScheduled) {
      return;
    } else {
      isScheduled = true;
    }
    nodeContext.setAttached(false);
    new Thread(this).start();
  }

  @Override
  public void run() {
    while (!nodeContext.isAttached()) {
      try {
        nodeControlBean.attachNode(nodeContext.getManagerIp(), nodeContext.getNodeIp());
        synchronized (this) {
          isScheduled = false;
        }
        break;
      } catch (Exception e) {
        log.error("Exception occurred during reconnection", e);
      }
      try {
        Thread.sleep(reconnectIntervalInMin * MINUTE_IN_MILLIS);
      } catch (InterruptedException e) {
        log.error("Exception occurred during sleeping a thread", e);
      }
    }
  }

  public void setNodeContext(NodeContext nodeContext) {
    this.nodeContext = nodeContext;
  }

  public void setNodeControlBean(NodeControlBean nodeControlBean) {
    this.nodeControlBean = nodeControlBean;
  }

  public void setReconnectIntervalInMin(int reconnectIntervalInMin) {
    this.reconnectIntervalInMin = reconnectIntervalInMin;
  }
}
